// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: jshin

#pragma once

#include <chrono>

#include <glog/logging.h>

class MarketTimestampProvider {
 public:
  MarketTimestampProvider() = default;

  int64_t market_ts() const { return market_ts_; }
  int64_t system_ts() const { return system_ts_; }
  int64_t realsystem_ts() const { return realsystem_ts_ = GetTimestamp(); return realsystem_ts_; }

  void PrintLog() const {
    LOG(INFO) << " " << market_ts() << " " << system_ts();
  }

  void Initialize(int64_t market_ts) {
    CHECK_LT(0, market_ts) << market_ts;
    CHECK_LE(market_ts_, market_ts) << market_ts_ << " " << market_ts;
    CHECK_EQ(0, market_ts_) << market_ts_ << " " << market_ts;
    market_ts_ = market_ts;
    system_ts_ = GetTimestamp();
  }

  void Finalize(int64_t market_ts) {
    CHECK_LT(0, market_ts) << market_ts;
    CHECK_LE(market_ts_, market_ts) << market_ts_ << " " << market_ts;
    CHECK_NE(0, market_ts_) << market_ts_ << " " << market_ts;
    market_ts_ = market_ts;
    system_ts_ = GetTimestamp();
  }

  void Set(int64_t market_ts) {
    CHECK_LT(0, market_ts) << market_ts;
    CHECK_LE(market_ts_, market_ts) << market_ts_ << " " << market_ts;
    market_ts_ = market_ts;
    system_ts_ = GetTimestamp();
  }

  static int64_t GetTimestamp() {
    auto now = std::chrono::high_resolution_clock::now();
    return now.time_since_epoch().count();
  }

 protected:
  const int64_t min_market_ts_{0};
  const int64_t max_market_ts_{0};
  int64_t market_ts_{0};
  int64_t system_ts_{0};
  mutable int64_t realsystem_ts_{0};
};
